#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <config.h>
#include <systems.h>
#include <misc.h>

u8 buf[256];

int _round(double x)
{
#ifdef NIOS2_FPU_SUPPORT
    if((int)FPU_MUL(FPU_SUB((float)x,(int)x), 2) >= 1)
#else
    if(((int)((x - (int)x) * 2)) >= 1)
#endif
        return (int)x+1;
    else
        return (int)x;
}

inline char is_in_region(u32 x, u32 y, u32 reg_sx, u32 reg_sy, u32 reg_dx, u32 reg_dy)
{
    if(x - reg_sx > 0 && y - reg_sy > 0)
        if(reg_dx - x > 0 && reg_dy - y > 0)
            return 1;
    return 0;
}

/* remove directory prefix and file suffix from full path*/
u8 *_basename(u8 *path)
{
    u8 *p, *b;

    if(!path)
        return NULL;
    
    memset(buf, 0x0, 256);
    /* remove prepended path and extension*/
    b = path;
    for (p=path; *p; ++p) {
        if (*p == '/')
            b = p + 1;
    }
    strcpy(buf, b);
    for (p=buf; *p; ++p) {
        if (*p == '.') {
            *p = 0;
            break;
        }
    }
    return buf;
}

/* return file suffix from full path */
u8 *_suffix(u8 *path)
{
    u8 *p, *b;
    int i, j;

    if(!path)
        return NULL;
    
    //memset(buf, 0x0, 256);
    /* remove prepended path and extension*/
    b = path;
    for (p=path; *p; ++p) {
        if (*p == '.')
            b = p + 1;
    }
    i = strlen(b);
    j = strlen(path);
    if(i > 5 || i == j)
        return NULL; /* No suffix found */
    //strcpy(buf, b);
    return b;
}

char *_strnstr(const char *big, const char *little, int size)
{
    int i;
    int len;
    
    if(!big || !little || size < (len = strlen(little)))
        return NULL;
        
    for(i = 0; i < size; i++) {
        if(memcmp(&big[i], little, len) == 0)
            return (char *)&big[i];
    }
    
    return NULL;
}
